//
//  ViewController.m
//  NetworkingIsFun
//
//  Created by bubu on 07/06/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ViewController.h"
#import "AFNetworking.h"

@implementation ViewController

@synthesize tableView = _tableView, activityIndicatorView = _activityIndicatorView, movies = _movies;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Setting Up Table View
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.tableView.hidden = YES;
    [self.view addSubview:self.tableView];
    
    // Setting Up Activity Indicator View
    self.activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.activityIndicatorView.hidesWhenStopped = YES;
    self.activityIndicatorView.center = self.view.center;
    [self.view addSubview:self.activityIndicatorView];
    [self.activityIndicatorView startAnimating];
    
    // Initializing Data Source
    self.movies = [[NSArray alloc] init];
    
    //NSString *urlToCall = @"http://itunes.apple.com/search?term=harry&country=us&entity=movie";
    /*NSString *urlToCall = @"http://li419-131.members.linode.com/where/is/5434137746953/number/153153/lat/22.2222/lon/33.9999";
     
     NSURL *url = [[NSURL alloc] initWithString:urlToCall];
     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
     
     AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
     //self.movies = [JSON objectForKey:@"results"];
     self.movies = JSON;
     NSString *resultados = JSON;
     NSLog(@"%@", resultados);
     [self.activityIndicatorView stopAnimating];
     //[self.tableView setHidden:NO];
     //[self.tableView reloadData];
     
     } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
     NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
     }];
     
     [operation start];*/
    
    NSString *serverUrl = @"http://li419-131.members.linode.com/";
    NSString *path = @"/users/";
    //NSString *pathGet = @"/where/is/5434137746953/number/153153/lat/22.2222/lon/33.9999";
    //NSString *pathPost = @"number=11111&name=testServer&lat=32.5713&lon=60.3926";
    //NSString *pathPut = @"number=5434137746953&name=marcelo&lat=-11.1&lon=11.1";
    NSDictionary *parameters = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"88888",@"testServer",@"33.333",@"60.60",nil] forKeys:[NSArray arrayWithObjects:@"number",@"name",@"lat",@"lon",nil]];    
    
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:serverUrl]];
    
    NSMutableURLRequest *request;
    request = [httpClient requestWithMethod:@"POST" 
                                       path:path
                                 parameters:parameters];
    
    httpClient.parameterEncoding = AFFormURLParameterEncoding;
    NSLog(@"request: %@", request);
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        //self.movies = [JSON objectForKey:@"results"];
        //self.movies = JSON;
        NSString *resultados = JSON;
        NSLog(@"%@", resultados);
        [self.activityIndicatorView stopAnimating];
        //[self.tableView setHidden:NO];
        //[self.tableView reloadData];
        
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"Request Failed with Error: %@, error description: %@, error userinfo: %@", error, error.description, error.userInfo);
    }];
    
    [operation start];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.movies && self.movies.count) {
        return self.movies.count;
    } else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"Cell Identifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
    }
    
    /*NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
    cell.textLabel.text = [movie objectForKey:@"trackName"];
    cell.detailTextLabel.text = [movie objectForKey:@"artistName"];
    
    NSURL *url = [[NSURL alloc] initWithString:[movie objectForKey:@"artworkUrl100"]];
    NSData *data = [NSData dataWithContentsOfURL:url];
    cell.imageView.image = [[UIImage alloc] initWithData:data];*/
    
    return cell;
    
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end
